#pragma once
// ================== 包含头文件 ====================
#include "ti_msp_dl_config.h"
// ================== 包含头文件 ====================
#include <type_traits>
// ================== 硬件抽象层 ==================

namespace hal::details_timer
{
    // 定时器策略模板
    template<uint32_t TIMER_BASE>
    class timer_config
    {
    private:
        // 获取定时器硬件寄存器指针
        static GPTIMER_Regs *get_base()
        {
            return reinterpret_cast<GPTIMER_Regs *>(TIMER_BASE);
        }

    public:
        // 初始化（编译期计算时钟）
        template<uint32_t PSC, uint32_t ARR>
        static void init() noexcept
        {}

        // 运行时频率设置（强制内联）
        static inline void set_freq(const uint32_t freq) noexcept
        {

            // 获取当前总线时钟频率（需根据实际系统实现）
            const uint32_t bus_freq = CPUCLK_FREQ;

            // 计算所需的重载值 (ARR = F_bus / (PSC * freq) - 1)
            const uint32_t psc = get_base()->COMMONREGS.CPS;
            const uint32_t arr = (bus_freq / (psc + 1) / freq) - 1;

            // 设置新的重载值
            DL_Timer_setLoadValue(get_base(), arr);
        }

        static inline void start_IT() noexcept
        {
            // 清除定时器中断标志
            NVIC_ClearPendingIRQ(get_isr());

            // 使能定时器中断
            NVIC_EnableIRQ(get_isr());
        }

        static inline void start() noexcept
        { DL_Timer_startCounter(get_base()); }

        static inline void stop() noexcept
        { DL_Timer_stopCounter(get_base()); }

        // 获取SPI中断
        static constexpr IRQn_Type get_isr()
        {
            if constexpr (TIMER_BASE == TIMA0_BASE)
                return TIMG0_INT_IRQn;
            else if constexpr (TIMER_BASE == TIMG6_BASE)
                return TIMG6_INT_IRQn;
            else if constexpr (TIMER_BASE == TIMG7_BASE)
                return TIMG7_INT_IRQn;
            else if constexpr (TIMER_BASE == TIMG8_BASE)
                return TIMG8_INT_IRQn;
            else if constexpr (TIMER_BASE == TIMG12_BASE)
                return TIMG12_INT_IRQn;
            else if constexpr (TIMER_BASE == TIMA0_BASE)
                return TIMA0_INT_IRQn;
            else if constexpr (TIMER_BASE == TIMA1_BASE)
                return TIMA1_INT_IRQn;
        }
    };
} // namespace hal



namespace hal
{
// ================== 用户接口别名 ==================
    using timera0 = details_timer::timer_config<TIMA0_BASE>;
    using timera1 = details_timer::timer_config<TIMA1_BASE>;
    using timerg0 = details_timer::timer_config<TIMG0_BASE>;
    using timerg6 = details_timer::timer_config<TIMG6_BASE>;
    using timerg7 = details_timer::timer_config<TIMG7_BASE>;
    using timerg8 = details_timer::timer_config<TIMG8_BASE>;
    using timerg12 = details_timer::timer_config<TIMG12_BASE>;
}
